package com.geeka.d12.work;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class TcpServerDemo2 {
    public static void main(String[] args) {
        /**
         * 服务端 1, 服务商可以连续接收客户端消息
         *       2, 当客户端与服务端建立连接,往客户端发送欢迎信息
         */
        String welcomeMsg = "欢迎进入聊天室...";
        try (ServerSocket serverSocket = new ServerSocket(7777);
        ) {
            //阻塞等待别人连接, 有人连接才会继续执行
            // clientSocket 指向链接上来的客户端
            System.out.println("服务端启动: " + serverSocket.getLocalPort());
            Socket clientSocket = null;

            InputStream clientIps = null;
            BufferedReader br = null;


            // serverSocket.accept 是阻塞方法, 如果往下走,说明与客户端建立连接
            clientSocket = serverSocket.accept();
//            System.out.println(clientSocket);
            // 通过输出流向客户端发送消息
            OutputStream ops = clientSocket.getOutputStream();
            PrintStream ps = new PrintStream(ops);
            ps.println(welcomeMsg);
            clientIps = clientSocket.getInputStream();
            br = new BufferedReader(new InputStreamReader(clientIps));
            String msg = null;
            while ((msg = br.readLine()) != null) {
                SocketAddress remoteSocketAddress = clientSocket.getRemoteSocketAddress();
                System.out.println(remoteSocketAddress + "对方说: " + msg);

            }
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
